package com.mong.demo.controller;

import com.mong.demo.pojo.User;
import com.mong.demo.service.UserService;
import com.mong.demo.utils.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/save")
    @ResponseBody
    public ResultData saveUser(User user){
        ResultData result = new ResultData();
        try {
            userService.saveUser(user);
            result.setStatus(200);
        }catch (Exception ex){
            result.setMsg("失败"+ex.getMessage());
            result.setStatus(0);
        }
        return result;
    };

    @GetMapping("/find")
    @ResponseBody
    public ResultData findUserByUserName(String username){
        ResultData result = new ResultData();
        try {
           User user=  userService.findUserByUserName(username);
            result.setStatus(200);
            result.setData(user);
        }catch (Exception ex){
            result.setMsg("失败"+ex.getMessage());
            result.setStatus(0);
        }
        return result;
    };


    @GetMapping("/update")
    @ResponseBody
    public ResultData updateUser(User user){
        ResultData result = new ResultData();
        try {
            userService.updateUser(user);
            result.setStatus(200);
            result.setData(user);
        }catch (Exception ex){
            result.setMsg("失败"+ex.getMessage());
            result.setStatus(0);
        }
        return result;
    };

    @GetMapping("/delete")
    @ResponseBody
    public ResultData deleteUserById(Long id){
        ResultData result = new ResultData();
        try {
            userService.deleteUserById(id);
            result.setStatus(200);
        }catch (Exception ex){
            result.setMsg("失败"+ex.getMessage());
            result.setStatus(0);
        }
        return result;
    };

}
